<?php

namespace app\department\controller;

use app\department\model\DepartmentConfigItemModel;
use app\department\model\DepartmentConfigModel;
use app\department\model\DepartmentModel;
use app\department\model\RoleModel;
use cmf\controller\AdminBaseController;
use tree\Tree;

/**
 * Class DepartmentController
 * @package app\department\controller
 * @adminMenuRoot(
 *     'name'   =>'部门管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 30,
 *     'icon'   =>'th',
 *     'remark' =>'部门管理'
 * )
 */
class DepartmentController extends AdminBaseController
{

    /**
     * 部门列表
     * @adminMenu(
     *     'name'   => '部门列表',
     *     'parent' => 'department/department/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 100,
     *     'icon'   => '',
     *     'remark' => '部门列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $where = [
            'status' => 1
        ];
        if($admin_id != 1) {
            $where['id'] = ['in',getUsersGroup($admin_id)];
            $department = get_user_group($admin_id);
            $departments = getParent('department',$department[0],['id','lvl','is_company']);
            $parent = [];
            foreach ($departments as $department) {
                if($department['is_company']) {
                    $parent = $department;
                    break;
                }
            }
        }
        $departmentModel = new DepartmentModel();
        $lists = $departmentModel->where($where)->order('list_order')->select()->toArray();

        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $parent_id = 999;
        foreach ($lists as $key => $value) {
            $lists[$key]['edit'] = url('edit', ['id' => $value['id']]);
            $lists[$key]['add'] = url('add', ['id' => $value['id']]);
            $lists[$key]['del'] = '';
            if($value['id'] != 1) {
                $lists[$key]['del'] = '<a class="js-ajax-dialog-btn" data-msg="是否确定删除？删除后无法恢复！" href="'.url('del',['id' => $value['id']]).'">删除</a>';
            }
            $lists[$key]['role'] = url('position/index', ['department_id' => $value['id']]);
            if($value['parent_id'] < $parent_id) $parent_id = $value['parent_id'];
            $lists[$key]['authority'] = '';
            $lists[$key]['config'] = '';
            if($value['is_company']) {
                if($admin_id ==1 || $parent['id'] != $value['id']) {
                    $lists[$key]['authority'] = '<a href="'.url('authority',['id' => $value['id']]).'">授权</a>';
                }
                if($admin_id == 1) {
                    $lists[$key]['config'] = '<a href="'.url('config',['pid' => $value['id']]).'">配置</a>';
                }
            }
        }

        $tree->init($lists);
        $str = "<tr>
                    <td style='padding-left:20px;'><input name='list_orders[\$id]' type='text' size='3' value='\$list_order' class='input input-order'></td>
					<td>\$spacer\$name</td>
					<td>\$description</td>
					<td>
						<a href='\$add'>新增下属部门</a>
						<a href='\$edit'>编辑</a>
						\$del
						<a href='\$role'>职位管理</a>
						\$authority
						\$config
					</td>
                </tr>";
        $category = $tree->getTree($parent_id, $str);
        $this->assign("category", $category);

        $this->assign('lists', $lists);
        $this->assign('parent_id', $parent_id);
        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 101,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        $departmentModel = new DepartmentModel();
        if ($this->request->isPost()) {
            $arrData = $this->request->post();

            $result = $departmentModel->allowField(true)->validate(true)->save($arrData);
            if ($result) {
                $this->success(lang("ADD_SUCCESS"), url("index"));
            } else {
                $this->error($departmentModel->getError());
            }
        }
        $id = $this->request->param('id', 1, 'intval');
        $where = ['id' => $id];
        $default = $departmentModel->where($where)->find();

        $this->assign('default', $default);
        return $this->fetch();
    }

    /**
     * 编辑
     * @adminMenu(
     *     'name'   => '编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 102,
     *     'icon'   => '',
     *     'remark' => '编辑',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        $departmentModel = new DepartmentModel();
        if ($this->request->isPost()) {
            $arrData = $this->request->post();

            $result = $departmentModel->allowField(true)->validate(true)
                ->save($arrData, ["id" => $arrData["id"]]);

            if ($result) {
                $this->success(lang("SAVE_SUCCESS"), url("index"));
            } else {
                $this->error($departmentModel->getError());
            }
        }
        $intId = $this->request->param("id", 0, 'intval');

        $result = $departmentModel
            ->alias('department')
            ->field('department.*,fdepartment.name as parent_name')
            ->join('__DEPARTMENT__ fdepartment', 'department.parent_id = fdepartment.id', 'left')
            ->where(["department.id" => $intId])->find();

        $this->assign('result', $result);
        return $this->fetch();
    }

    function del() {
        $id = $this->request->param('id',0,'intval');
        $departmentModel = new DepartmentModel();
        $son_dep = $departmentModel
            ->where([
                'parent_id' => $id,
                'status' => 1
            ])
            ->find();
        if($son_dep) {
            $this->error('请先删除下级部门！');
        }
        $roleModel = new RoleModel();
        $role = $roleModel
            ->where([
                'department_id' => $id,
                'status' => 1
            ])
            ->find();
        if($role) {
            $this->error('请先删除部门内职位！');
        }
        $departmentModel->allowField(true)->save(['status' => 0],[
            'id' => $id
        ]);
        $this->success('删除成功！');
    }

    function select()
    {
        $id = $this->request->param('id', 0, 'intval');

        $admin_id = cmf_get_current_admin_id();
        $where = ['status' => 1];
        if($admin_id != 1) {
            $where['id'] = ['in',getUsersGroup($admin_id)];
        }

        $departmentModel = new DepartmentModel();

        $lists = $departmentModel->where($where)->select()->toArray();

        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $parent_id = 99999;
        foreach ($lists as $key => $value) {
            $lists[$key]['checked'] = ($id == $value['id']) ? 'checked' : '';
            if($value['parent_id'] < $parent_id) $parent_id = $value['parent_id'];
        }

        $tree->init($lists);
        $str = "<tr class='data-item-tr'>
                        <td><input type='radio' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='id'
                               value='\$id' data-name='\$name' \$checked></td>
                        <td>\$spacer\$name</td>
                        <td>\$description</td>
                    </tr>";
        $category = $tree->getTree($parent_id, $str);
        $this->assign("category", $category);

        return $this->fetch();
    }



    /**
     * 授权
     * @adminMenu(
     *     'name'   => '授权',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '授权',
     *     'param'  => ''
     * )
     */
    public function authority()
    {
        if ($this->request->isPost()) {
            $roleId = $this->request->param("roleId", 0, 'intval');
            if (!$roleId) {
                $this->error("需要授权的公司不存在！");
            }
            if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {
                db("authAccess")->where(["role_id" => $roleId, 'type' => 'company'])->delete();
                $menus = [];
                foreach ($_POST['menuId'] as $menuId) {
                    $menu = db("adminMenu")->where(["id" => $menuId])->field("app,controller,action")->find();
                    if ($menu) {
                        $app = $menu['app'];
                        $model = $menu['controller'];
                        $action = $menu['action'];
                        $name = strtolower("$app/$model/$action");
                        $menus[] = ["role_id" => $roleId, "rule_name" => $name, 'type' => 'company'];
                    }
                }
                if($menus) {
                    db("authAccess")->insertAll($menus);
                }

                $this->success("授权成功！");
            } else {
                //当没有数据时，清除当前角色授权
                db("authAccess")->where(["role_id" => $roleId, 'type' => 'company'])->delete();
                $this->error("没有接收到数据，执行清除授权成功！");
            }
        }
        //角色ID
        $roleId = $this->request->param("id", 0, 'intval');
        if (empty($roleId)) {
            $this->error("参数错误！");
        }

        $tree = new Tree();
        $tree->icon = ['│ ', '├─ ', '└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $result = db('admin_menu')
            ->alias('admin_menu')
            ->select();

        $privilegeData = db("authAccess")->where(["role_id" => $roleId, 'type' => 'company'])->column("rule_name");//获取权限表数据

        $departments = getParent('department',$roleId,['id','lvl','is_company']);
        $parent = [];
        foreach ($departments as $department) {
            if($department['id'] == $roleId) continue;
            if($department['is_company']) {
                $parent = $department;
                $departmentData = db("authAccess")->where(["role_id" => $department['id'], 'type' => 'company'])->column("rule_name");//获取权限表数据
                break;
            }
        }

        $newMenus      = [];
        $hide = [];
        $res = [];
        foreach ($result as $m) {
            if($parent) {
                if(!$this->_isChecked($m, $departmentData)) {
                    continue;
                }
            }
            if($m['is_hide']){
                $hide[] = $m['id'];
                continue;
            };
            if(in_array($m['parent_id'],$hide)){
                $hide[] = $m['id'];
                continue;
            };
            $res[] = $m;
            $newMenus[$m['id']] = $m;
        }
        $result = $res;

        foreach ($result as $n => $t) {
            $result[$n]['checked']      = ($this->_isChecked($t, $privilegeData)) ? ' checked' : '';
            $result[$n]['level']        = $this->_getLevel($t['id'], $newMenus);
            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';
            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
        }

        $str = "<tr id='node-\$id'\$parentIdNode  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' level='\$level' \$checked  onclick='javascript:checknode(this);'> \$name</td>
    			</tr>";
        $tree->init($result);

        $category = $tree->getTree(0, $str);

        $roleDepartment = db('role_department')->where([
            'role_id' => $roleId
        ])->find();

        $this->assign("category", $category);
        $this->assign("roleDepartment", $roleDepartment);
        $this->assign("roleId", $roleId);
        return $this->fetch();
    }

    /**
     * 获取菜单深度
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    protected function _getLevel($id, $array = [], $i = 0)
    {
        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
            return $i;
        } else {
            $i++;
            return $this->_getLevel($array[$id]['parent_id'], $array, $i);
        }
    }

    /**
     * 检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param $privData
     * @return bool
     */
    private function _isChecked($menu, $privData)
    {
        $app    = $menu['app'];
        $model  = $menu['controller'];
        $action = $menu['action'];
        $name   = strtolower("$app/$model/$action");
        if ($privData) {
            if (in_array($name, $privData)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    function config() {
        $pid = $this->request->param('pid',0,'intval');
        $departmentConfigModel = new DepartmentConfigModel();
        $lists = $departmentConfigModel
            ->where([
                'pid' => $pid
            ])
            ->paginate();

        $this->assign('lists',$lists);
        $this->assign('pid',$pid);
        $this->assign('page',$lists->render());
        return $this->fetch();
    }

    function config_add() {
        $pid = $this->request->param('pid',0,'intval');
        if($this->request->isPost()) {
            $arrData = $this->request->post();
            $departmentConfigModel = new DepartmentConfigModel();
            $departmentConfigModel->save($arrData);
            $this->success('添加成功！',url('config',['pid' => $pid]));
        }
        $this->assign('pid',$pid);
        return $this->fetch();
    }

    function config_edit() {
        $id = $this->request->param('id',0,'intval');
        $departmentConfigModel = new DepartmentConfigModel();
        $result = $departmentConfigModel->find($id);
        if(!$result) {
            $this->error('参数错误！');
        }
        if($this->request->isPost()) {
            $arrData = $this->request->post();
            $departmentConfigModel->save($arrData,['id' => $id]);
            $this->success('保存成功！',url('config',['pid' => $result['pid']]));
        }

        $this->assign('result',$result);
        $this->assign('id',$id);
        return $this->fetch();
    }

    function item() {
        $pid = $this->request->param('pid',0,'intval');
        $departmentConfigItemModel = new DepartmentConfigItemModel();
        $lists = $departmentConfigItemModel
            ->where([
                'pid' => $pid
            ])
            ->paginate();

        $this->assign('lists',$lists);
        $this->assign('pid',$pid);
        $this->assign('page',$lists->render());
        return $this->fetch();
    }

    function item_add() {
        $pid = $this->request->param('pid',0,'intval');
        if($this->request->isPost()) {
            $arrData = $this->request->post();
            $departmentConfigItemModel = new DepartmentConfigItemModel();
            $departmentConfigItemModel->save($arrData);
            $this->success('添加成功！',url('item',['pid' => $pid]));
        }
        $this->assign('pid',$pid);
        return $this->fetch();
    }

    function item_edit() {
        $id = $this->request->param('id',0,'intval');
        $departmentConfigItemModel = new DepartmentConfigItemModel();
        $result = $departmentConfigItemModel->find($id);
        if(!$result) {
            $this->error('参数错误！');
        }
        if($this->request->isPost()) {
            $arrData = $this->request->post();
            $departmentConfigItemModel->save($arrData,['id' => $id]);
            $this->success('保存成功！',url('item',['pid' => $result['pid']]));
        }

        $this->assign('result',$result);
        $this->assign('id',$id);
        return $this->fetch();
    }

    public function listOrder()
    {
        $departmentModel = new DepartmentModel();
        parent::listOrders($departmentModel);
        $this->success("排序更新成功！");
    }
}